<template>
  <view class="page-container w-[750rpx] mx-auto bg-[#f5f5f5] min-h-screen">
    <!-- 页头 -->
    <PageHeader title="发布课程"/>

    <!-- 表单容器 -->
    <view class="form-container p-[24rpx]">
      <!-- 课程基本信息 -->
      <view class="form-section bg-white rounded-[8rpx] p-[24rpx] mb-[30rpx]">
        <text class="section-title text-[28rpx] font-bold mb-[24rpx] block text-blue-500">课程基本信息</text>

        <!-- 课程标题 -->
        <view class="form-group mb-[30rpx]">
          <text class="form-label block mb-[16rpx] text-[24rpx] text-[#666]">课程标题</text>
          <nut-input v-model="courseForm.title" placeholder="请输入课程标题"
                     class="w-full p-[20rpx] border-[1rpx] border-[#ddd] rounded-[8rpx] text-[24rpx]"/>
        </view>

        <!-- 课程封面 -->
        <view class="form-group mb-[30rpx]">
          <text class="form-label block mb-[16rpx] text-[24rpx] text-[#666]">课程封面</text>
          <view
              class="upload-area border-[1rpx] border-dashed border-[#ddd] rounded-[8rpx] p-[40rpx] text-center cursor-pointer mb-[20rpx]"
              @click="chooseCourseCover">
            <text class="upload-icon block text-[48rpx] text-blue-500 mb-[10rpx]">+</text>
            <text class="upload-text block text-[24rpx] text-[#666]">点击上传课程封面</text>
            <image :src="courseCover" v-if="courseCover"
                   class="preview-image w-full max-h-[400rpx] mt-[20rpx]" mode="widthFix"/>
          </view>
        </view>

        <!-- 课程简介 -->
        <view class="form-group mb-[30rpx]">
          <text class="form-label block mb-[16rpx] text-[24rpx] text-[#666]">课程简介</text>
          <nut-textarea v-model="courseForm.description" placeholder="请输入课程简介"
                        class="w-full p-[20rpx] border-[1rpx] border-[#ddd] rounded-[8rpx] text-[24rpx]"
                        :min-height="160"/>
        </view>

        <!-- 课程类型 -->
        <view class="form-group mb-[30rpx]">
          <text class="form-label block mb-[16rpx] text-[24rpx] text-[#666]">课程类型</text>
          <view class="type-options flex gap-[20rpx]">
            <view
                class="type-option flex-1 p-[20rpx] border-[1rpx] rounded-[8rpx] text-center cursor-pointer"
                :class="courseForm.type === 1 ? 'border-blue-500 bg-blue-50 text-blue-500' : 'border-gray-300 text-gray-500'"
                @click="courseForm.type = 1">
              <text class="block text-[24rpx]">视频列表</text>
            </view>
            <view
                class="type-option flex-1 p-[20rpx] border-[1rpx] rounded-[8rpx] text-center cursor-pointer"
                :class="courseForm.type === 2 ? 'border-blue-500 bg-blue-50 text-blue-500' : 'border-gray-300 text-gray-500'"
                @click="courseForm.type = 2">
              <text class="block text-[24rpx]">线下学习</text>
            </view>
          </view>
        </view>

        <!-- 课时 -->
        <!--        <view class="form-group mb-[30rpx]">-->
        <!--          <text class="form-label block mb-[16rpx] text-[24rpx] text-[#666]">课时</text>-->
        <!--          <nut-textarea v-model="courseForm.cycle" placeholder="请输入课时"-->
        <!--                        class="w-full p-[20rpx] border-[1rpx] border-[#ddd] rounded-[8rpx] text-[24rpx]"-->
        <!--                        :min-height="160"/>-->
        <!--          &lt;!&ndash; 基于 cycleTypeOptions 渲染单选框组 &ndash;&gt;-->
        <!--          <view class="form-group">-->
        <!--            <text class="label">课时类型</text>-->
        <!--            <view-->
        <!--                class="picker-input"-->
        <!--                :class="{ 'error-border': formErrors.type }"-->
        <!--                @click="showTypePicker = true"-->
        <!--            >-->
        <!--              <text class="picker-text">{{ courseForm.cycleType || '请选择课时类型' }}</text>-->
        <!--            </view>-->
        <!--          </view>-->
        <!--            &lt;!&ndash; 选择器弹窗 &ndash;&gt;-->
        <!--            <nut-popup v-model:visible="showTypePicker" position="bottom" round>-->
        <!--              <nut-picker-->
        <!--                  v-model="cycleTypesValue"-->
        <!--                  :columns="cycleTypeOptions"-->
        <!--                  title="选择职位类型"-->
        <!--                  @confirm="onTypeConfirm"-->
        <!--                  @cancel="showTypePicker = false"-->
        <!--              />-->
        <!--            </nut-popup>-->
        <!--        </view>-->


        <!-- 课程价格 -->
        <view class="form-group mb-[30rpx]">
          <text class="form-label block mb-[16rpx] text-[24rpx] text-[#666]">课程价格 (元)</text>
          <nut-input v-model="courseForm.price" type="number" placeholder="请输入课程价格" min="0" step="0.01"
                     class="w-full p-[20rpx] border-[1rpx] border-[#ddd] rounded-[8rpx] text-[24rpx]"/>
        </view>

        <!-- 课程周期 -->
        <!-- <view class="form-group mb-[30rpx]">
          <text class="form-label block mb-[16rpx] text-[24rpx] text-[#666]">课程周期</text>
          <view class="cycle-inputs flex gap-[20rpx] items-center">
            <nut-input v-model="courseForm.cycle" type="number" placeholder="请输入周期"
              class="flex-1 p-[20rpx] border-[1rpx] border-[#ddd] rounded-[8rpx] text-[24rpx]" />
            <view class="cycle-type-selector">
              <nut-picker v-model="courseForm.cycleType" :columns="cycleTypeOptions" placeholder="选择周期类型"
                class="p-[20rpx] border-[1rpx] border-[#ddd] rounded-[8rpx] text-[24rpx] min-w-[120rpx]" />
            </view>
          </view>
        </view> -->
      </view>

      <!-- 老师信息 -->
      <view class="form-section bg-white rounded-[8rpx] p-[24rpx] mb-[30rpx]">
        <text class="section-title text-[28rpx] font-bold mb-[24rpx] block text-[#2196F3]">老师信息</text>

        <!-- 老师名称 -->
        <view class="form-group mb-[30rpx]">
          <text class="form-label block mb-[16rpx] text-[24rpx] text-[#666]">老师名称</text>
          <nut-input v-model="courseForm.teacherName" placeholder="请输入老师名称"
                     class="w-full p-[20rpx] border-[1rpx] border-[#ddd] rounded-[8rpx] text-[24rpx]"/>
        </view>

        <!-- 老师图片 -->
        <view class="form-group mb-[30rpx]">
          <text class="form-label block mb-[16rpx] text-[24rpx] text-[#666]">老师图片</text>
          <view
              class="upload-area border-[1rpx] border-dashed border-[#ddd] rounded-[8rpx] p-[40rpx] text-center cursor-pointer mb-[20rpx]"
              @click="chooseTeacherPic">
            <text class="upload-icon block text-[48rpx] text-blue-500 mb-[10rpx]">+</text>
            <text class="upload-text block text-[24rpx] text-[#666]">点击上传老师图片</text>
            <image :src="teacherPhoto" v-if="teacherPhoto"
                   class="preview-image w-full max-h-[400rpx] mt-[20rpx]" mode="widthFix"/>
          </view>
        </view>

        <!-- 老师介绍 -->
        <view class="form-group mb-[30rpx]">
          <text class="form-label block mb-[16rpx] text-[24rpx] text-[#666]">老师介绍</text>
          <nut-textarea v-model="courseForm.teachersIntroduction" placeholder="请输入老师介绍"
                        class="w-full p-[20rpx] border-[1rpx] border-[#ddd] rounded-[8rpx] text-[24rpx]"
                        :min-height="160"/>
        </view>
      </view>

      <!-- 课程章节 -->
      <view class="form-section bg-white rounded-[8rpx] p-[24rpx] mb-[30rpx]">
        <text class="section-title text-[28rpx] font-bold mb-[24rpx] block text-[#2196F3]">课程章节</text>

        <view id="lessons-container">
          <!-- 章节列表 - 使用v-for渲染 -->
          <view class="lesson-item bg-[#f9f9f9] rounded-[8rpx] p-[30rpx] mb-[30rpx] relative"
                v-for="(lesson, index) in lessons" :key="lesson.id">
            <text
                class="remove-lesson absolute right-[20rpx] top-[20rpx] text-[#f44336] text-[36rpx] cursor-pointer"
                @click="removeLesson(index)">×
            </text>

            <!-- 章节标题 -->
            <view class="form-group mb-[30rpx]">
              <text class="form-label block mb-[16rpx] text-[24rpx] text-[#666]">章节标题</text>
              <nut-input v-model="lesson.title" placeholder="请输入章节标题"
                         class="w-full p-[20rpx] border-[1rpx] border-[#ddd] rounded-[8rpx] text-[24rpx]"/>
            </view>

            <!-- 章节封面 -->
            <view class="form-group mb-[30rpx]">
              <text class="form-label block mb-[16rpx] text-[24rpx] text-[#666]">章节封面 (可选)</text>
              <view
                  class="upload-area border-[1rpx] border-dashed border-[#ddd] rounded-[8rpx] p-[40rpx] text-center cursor-pointer mb-[20rpx]"
                  @click="chooseLessonCover(index)">
                <text class="upload-icon block text-[48rpx] text-[#2196F3] mb-[10rpx]">+</text>
                <text class="upload-text block text-[24rpx] text-[#666]">点击上传章节封面</text>
                <image :src="lesson.coverUrl" v-if="lesson.coverUrl"
                       class="preview-image w-full max-h-[400rpx] mt-[20rpx]" mode="widthFix"/>
              </view>
            </view>

            <!-- 章节视频 -->
            <view class="form-group mb-[30rpx]">
              <text class="form-label block mb-[16rpx] text-[24rpx] text-[#666]">章节视频</text>
              <view
                  class="upload-area border-[1rpx] border-dashed border-[#ddd] rounded-[8rpx] p-[40rpx] text-center cursor-pointer mb-[20rpx]"
                  @click="chooseLessonVideo(index)">
                <text class="upload-icon block text-[48rpx] text-[#2196F3] mb-[10rpx]">+</text>
                <text class="upload-text block text-[24rpx] text-[#666]">点击上传章节视频</text>

                <video :src="chapterVideo" v-if="chapterVideo" class="video-preview w-full mt-[20rpx]"
                       controls/>
                <text v-if="lesson.videoInfo" class="video-info block text-[20rpx] text-[#666] mt-[10rpx]">{{
                    lesson.videoInfo
                  }}
                </text>
              </view>
            </view>
          </view>
        </view>

        <!-- 添加章节按钮 -->
        <nut-button type="default" @click="addLesson"
                    class="add-lesson-btn w-full max-w-[200rpx] !flex !mx-auto p-[20rpx_30rpx] text-[24rpx] rounded-none text-center cursor-pointer select-none mb-[30rpx] border-[1rpx] border-[#2196F3] text-[#2196F3]"
        >添加章节
        </nut-button>

      </view>
    </view>
    <view class="fixed bottom-0 left-0 right-0 bg-white p-[20rpx] flex justify-center items-center">
      <nut-button type="primary" @click="submitCourse"
                  class="!w-[540rpx] !flex"
      >发布课程
      </nut-button>
    </view>


  </view>

</template>

<script setup>
import {ref} from 'vue'
import Taro, {showToast} from '@tarojs/taro'
import {post} from "@/utils/request";
// import { NutInput, NutTextarea, NutButton } from '@nutui/nutui-taro'
//上传文件路径
const uploadUrl = '/file/upload'
//上传后的路径
const coverImagePath = ref('');

const showAvatarPreview = ref(false)

// 课程基本信息
const courseForm = ref({
  title: '',
  coverUrl: '',
  price: '',
  description: '',
  type: 1, // 课程类型：1-视频列表，2-线下学习
  cycle: '', // 周期
  cycleType: '', // 周期类型
  teacherName: '', // 老师名称
  teachersIntroduction: '', // 老师介绍
  teacherPic: '' // 老师图片
})

// 周期类型选项
const cycleTypeOptions = ref([
  {text: '天', value: '天'},
  {text: '周', value: '周'},
  {text: '月', value: '月'},
  {text: '年', value: '年'}
])
// /** 选择器显示状态 */
// const showTypePicker = ref(false)
// const cycleTypesValue = ref()
//
// /** 选择器确认事件 */
// function onTypeConfirm(value: any) {
//   if (value.selectedValue && value.selectedValue.length > 0) {
//     cycleTypesValue.value = value.selectedValue[0]
//     //jobTypes.value = categoryOptions.value.find(item => item.value === String(val.selectedValue[0]))?.text
//     courseForm.value.cycleType = <string>cycleTypeOptions.value.find(item => item.value === String(value.selectedValue[0]))?.text
//   }
//   showTypePicker.value = false
// }

// 章节列表
const lessons = ref([])
//课程封面
const courseCover = ref()
const courseCoverUrl = ref('')
//老师图片
const  teacherPhoto = ref()
const teacherPhotoUrl = ref('')
//章节视频
const chapterVideo = ref()
// 返回上一页
const navigateBack = () => {
  Taro.navigateBack()  // 替换 router.back()
}

// 选择课程封面
const chooseCourseCover = async () => {
  try {
    const res = await Taro.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera']
    })
    // 从选择结果中获取图片的本地临时路径
    const tempFilePath = res.tempFilePaths[0];
    if (!tempFilePath) {
      Taro.showToast({ title: '未选择图片', icon: 'none' });
      return;
    }
    courseCover.value = tempFilePath
    // 调用上传接口，传入章节封面路径变量引用
    await uploadAvatar(tempFilePath,1)
  } catch (err) {
    console.error('选择图片失败', err)
  }
}

// 选择老师图片
const chooseTeacherPic = async () => {
  try {
    const res = await Taro.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera']
    })
    // 从选择结果中获取图片的本地临时路径
    const tempFilePath = res.tempFilePaths[0]
    teacherPhoto.value = tempFilePath
    // 调用上传接口，传入老师图片引用变量
    await uploadAvatar(tempFilePath,2)
  } catch (err) {
    console.error('选择老师图片失败', err)
  }
}
//上传文件
const uploadAvatar = async (filePath,targetPathRef) => {
  try {
    Taro.showLoading({ title: '上传中...' })
    const uploadRes = await Taro.uploadFile({
      url:'/file/upload',
      filePath,
      name: 'file',
      header: {
        'token': Taro.getStorageSync('token') ? Taro.getStorageSync('token') : ''
      }
    })
    Taro.hideLoading()
    const data = JSON.parse(uploadRes.data)
    if (data.code === 0) {
      if(targetPathRef===1){
        courseForm.value.coverUrl = data.data
      }else if (targetPathRef===2){
        courseForm.value.teacherPic = data.data
      }
      //console.log("targetPathRef",targetPathRef)
      showToast({ title: '上传成功', icon: 'success' })
    } else {
      showToast({ title: data.message || '上传失败', icon: 'none' })
    }
  } catch (err) {
    Taro.hideLoading()
    showToast({ title: '上传失败', icon: 'none' })
  }
}

// 添加章节
const addLesson = () => {
  lessons.value.push({
    id: Date.now(),
    title: '',
    coverUrl: '',
    videoUrl: '',
    videoInfo: ''
  })
}

// 初始化添加一个章节
addLesson()

// 删除章节
const removeLesson = (index) => {
  if (lessons.value.length <= 1) {
    Taro.showToast({
      title: '至少保留一个章节',
      icon: 'none',
      duration: 2000
    })
    return
  }
  lessons.value.splice(index, 1)
}

// 选择章节封面
const chooseLessonCover = async (index) => {
  try {
    const res = await Taro.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera']
    })
    const tempFilePath = res.tempFilePaths[0]
    lessons.value[index].coverUrl = tempFilePath
    // 上传章节封面到服务器
    await uploadLessonCover(tempFilePath, index)
  } catch (err) {
    console.error('选择图片失败', err)
    Taro.showToast({ title: '选择图片失败', icon: 'none' })
  }
}

// 选择章节视频
const chooseLessonVideo = async (index) => {
  try {
    const res = await Taro.chooseVideo({
      sourceType: ['album', 'camera'],
      maxDuration: 3600, // 最大60分钟
      camera: 'back'
    })
    
    lessons.value[index].videoUrl = res.tempFilePath
    lessons.value[index].duration = res.duration
    lessons.value[index].videoInfo = `已选择: ${res.duration.toFixed(1)}秒 (${formatFileSize(res.size)})`
    
    // 上传章节视频到服务器
    await uploadLessonVideo(res.tempFilePath, index, res.duration, res.size)
  } catch (err) {
    console.error('选择视频失败', err)
    Taro.showToast({ title: '选择视频失败', icon: 'none' })
  }
}

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 上传章节封面
const uploadLessonCover = async (filePath, index) => {
  try {
    Taro.showLoading({ title: '上传封面中...' })
    const uploadRes = await Taro.uploadFile({
      url: '/file/upload',
      filePath,
      name: 'file',
      header: {
        'token': Taro.getStorageSync('token') || ''
      }
    })
    Taro.hideLoading()
    
    const data = JSON.parse(uploadRes.data)
    if (data.code === 0) {
      lessons.value[index].coverUrl = data.data // 更新为服务器URL
      Taro.showToast({ title: '封面上传成功', icon: 'success' })
    } else {
      Taro.showToast({ title: data.message || '封面上传失败', icon: 'none' })
    }
  } catch (err) {
    Taro.hideLoading()
    Taro.showToast({ title: '封面上传失败', icon: 'none' })
  }
}

// 上传章节视频
const uploadLessonVideo = async (filePath, index, duration, size) => {
  try {
    Taro.showLoading({ title: '上传视频中...' })
    
    const uploadRes = await Taro.uploadFile({
      url: '/file/upload',
      filePath,
      name: 'file',
      header: {
        'token': Taro.getStorageSync('token') || ''
      },
      onProgressUpdate: (res) => {
        // 显示上传进度
        const progress = Math.round(res.progress)
        Taro.showLoading({ title: `上传中 ${progress}%` })
      }
    })
    
    Taro.hideLoading()
    const data = JSON.parse(uploadRes.data)
    
    if (data.code === 0) {
      lessons.value[index].videoUrl = data.data // 更新为服务器URL
      lessons.value[index].videoInfo = `上传成功: ${duration.toFixed(1)}秒 (${formatFileSize(size)})`
      Taro.showToast({ title: '视频上传成功', icon: 'success' })
    } else {
      lessons.value[index].videoInfo = '上传失败'
      Taro.showToast({ title: data.message || '视频上传失败', icon: 'none' })
    }
  } catch (err) {
    Taro.hideLoading()
    lessons.value[index].videoInfo = '上传失败'
    Taro.showToast({ title: '视频上传失败', icon: 'none' })
  }
}

// 提交课程
const submitCourse = async () => {
  // 验证课程基本信息
  if (!courseForm.value.title.trim()) {
    Taro.showToast({title: '请填写课程标题', icon: 'none'})
    return
  }
  
  if (!courseForm.value.price || Number(courseForm.value.price) < 0) {
    Taro.showToast({title: '请填写有效的课程价格', icon: 'none'})
    return
  }
  
  // 验证章节信息
  if (lessons.value.length === 0) {
    Taro.showToast({ title: '请至少添加一个章节', icon: 'none' })
    return
  }
  
  // 验证所有章节是否已上传视频
  for (let i = 0; i < lessons.value.length; i++) {
    const lesson = lessons.value[i]
    if (!lesson.title.trim()) {
      Taro.showToast({ title: `第${i + 1}章请填写章节标题`, icon: 'none' })
      return
    }
    if (!lesson.videoUrl || lesson.videoUrl.startsWith('http://tmp')) {
      Taro.showToast({ title: `第${i + 1}章请上传章节视频`, icon: 'none' })
      return
    }
  }
  
  Taro.showLoading({title: '发布中...'})
  
  try {
    // 计算总时长
    const totalDuration = lessons.value.reduce((sum, lesson) => sum + (Number(lesson.duration) || 0), 0)
    
    // 提交主数据
    const submitData = {
      title: courseForm.value.title,
      price: courseForm.value.price,
      cover: courseForm.value.coverUrl,
      description: courseForm.value.description,
      type: courseForm.value.type,
      cycle: totalDuration, // 使用总时长作为课时
      cycleType: '秒',
      teacherName: courseForm.value.teacherName,
      teachersIntroduction: courseForm.value.teachersIntroduction,
      teacherPic: courseForm.value.teacherPic
    }
    
    const mainRes = await post('/training/saveMain', submitData)
    if (mainRes.code !== 0) {
      throw new Error(mainRes.message || '保存失败')
    }
    
    const mainId = mainRes.data.id
    
    // 提交章节数据
    const submitDataLessons = lessons.value.map(lesson => ({
      title: lesson.title,
      videoUrl: lesson.videoUrl,
      coverUrl: lesson.coverUrl, // 添加章节封面
      duration: lesson.duration,
      trainingId: mainId
    }))
    
    const lessonsRes = await post('/training/saveList', submitDataLessons)
    if (lessonsRes.code === 0) {
      Taro.hideLoading()
      Taro.showToast({title: '课程发布成功', icon: 'success'})
      // 发布成功后返回上一页
      setTimeout(() => {
        Taro.navigateBack()
      }, 1500)
    } else {
      throw new Error(lessonsRes.message || '章节保存失败')
    }
  } catch (error) {
    Taro.hideLoading()
    Taro.showToast({title: error.message || '发布失败', icon: 'none'})
  }
}
</script>

<style scoped>
/* UnoCSS已通过类名处理样式，此处无需额外样式 */
</style>